axios.defaults.baseURL = 'https://hmajax.itheima.net'
//轻提示
function strap(msg) {
    const toast = document.querySelector('.toast')
    const tsbody = document.querySelector('.toast-body')
    const dialog = new bootstrap.Toast(toast)
    dialog.show()
    tsbody.innerHTML = msg
}
//
function checkLogin() {
    const token = localStorage.getItem('token')
    if (!token) {
        location.href = 'login.html'
    }
}
//
function logout() {
    const logout = document.querySelector('#logout')
    logout.addEventListener('click', function () {
        localStorage.removeItem('username')
        localStorage.removeItem('token')
        location.href = 'login.html'
    })
}
//请求拦截器
axios.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.authorization = token
    }
    return config
}, function (error) {
    return Promise.reject(error)
})
//响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    // console.log('response', response);
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log(error.response.status);
    //检查token是否过期或者被篡改
    if (error.response.status === 401) {
        localStorage.removeItem('username')
        localStorage.removeItem('token')
        setTimeout(() => {
            location.href = 'login.html'
        }, 1000);
    }
    return Promise.reject(error);
});